package com.ibm.spatiotemp.server.connections;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.amazonaws.auth.AWSCredentials;
import com.ibm.spatiotemp.server.config.LocalConfig;
import com.ibm.spatiotemp.server.constants.Constant;
import com.ibm.spatiotemp.tools.jsonParser;

public class ConnectionManager {
	public static Logger logger = Logger.getLogger(ConnectionManager.class);

	public static final int FreeScale = 5;
	public static ConcurrentHashMap<String, Connection[]> connectionPool = new ConcurrentHashMap<String, Connection[]>();
	
	public static Connection GetConnection(String conn_string) throws SQLException
	{
		Connection[] connpool = connectionPool.get(conn_string);
		Random random = new Random();
		int choice_idx = Math.abs(random.nextInt())%FreeScale;
		if(connpool == null){
			connpool = new Connection[FreeScale];
			Connection Conn = GetConnection_internal(conn_string);
			connpool[choice_idx] = Conn;
			connectionPool.put(conn_string, connpool);
			return Conn;
		}
		else if(connpool[choice_idx] == null){
			Connection Conn = GetConnection_internal(conn_string);
			connpool[choice_idx] = Conn;
			connectionPool.put(conn_string, connpool);
			return Conn;
		}
		else
			return connpool[choice_idx]; 
	}
	
	protected static Connection GetConnection_internal(String conn_string)
			throws SQLException {
		Connection testConn = null;
		String connStr = conn_string;
		
		if(conn_string.contains("AWSCREDENTIAL")){
			/*todo: parse credentials here*/
			AWSCredentials localcredentials = null;
			if(LocalConfig.Dynamodb_runningMode == DynamodbConnection.LocalMode){
		        localcredentials = new AWSCredentials() {
					@Override
					public String getAWSSecretKey() {
						return "a";
					}
					@Override
					public String getAWSAccessKeyId() {
						return "b";
					}
				};
			}
			else{//parse the credential in conn_string (as json format) here
				
			}
			
			DynamodbConnection conn = 
					new DynamodbConnection(localcredentials, 
							DynamodbConnection.LocalMode);
			return conn;
		}
		
		try {
			testConn = DriverManager.getConnection(connStr);
			testConn.setAutoCommit(true);

			logger.info(connStr);
			return testConn;
		} catch (SQLException e) {
			logger.error(e.getMessage() + "\n detail: "
					+ jsonParser.toJsonString(e.getStackTrace()));
			return null;
		}
	}
	
	public static Connection GetTestConnection(boolean persistency)
			throws SQLException {
		Connection testConn = null;
		/*
		 * using hsqldb in In-Process Mode, creating test db via jdbc connecton
		 * string connStr
		 */
		String connStr = Constant.DB_CLASS_MOCK_CONSTRING_MEM;
		if (persistency) {
			connStr = Constant.DB_CLASS_MOCK_CONSTRING_FILE;
		}
		try {
			/* for class path */
			@SuppressWarnings("unused")
			org.hsqldb.jdbcDriver driver = null;
			/* why hot ? Class.forName("org.hsqldb.jdbcDriver"); */
			testConn = DriverManager.getConnection(connStr);
			testConn.setAutoCommit(true);

			logger.info(connStr);
			return testConn;
		} catch (SQLException e) {
			logger.error(e.getMessage() + "\n detail: "
					+ jsonParser.toJsonString(e.getStackTrace()));
			return null;
		}
	}

}
